package com.epfresh.supplier.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.epfresh.api.constant.AppSupplyRouterConstant;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.api.utils.InputControl;
import com.epfresh.supplier.R;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.utils.T;
import com.epfresh.api.utils.ToastUtils;
import com.epfresh.supplier.constant.Constant;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;

public class RegisterActivity extends BaseActivity {

    public static final String TAG = "RegisterActivity";
    // 手机号,验证码，密码
    private String phoneSting, codeString, passwordString;
    private EditText phoneEt;
    private EditText codeEt;
    private EditText passwordEt;
    private TextView getcodeTv;
    private Button sureBu;
    private ImageView look_password;
    private FrameLayout look_frame;
    private ImageView read_flag;
    private View readLl;
    private boolean isRequestCode;
    private boolean isDestory;
    private FrameLayout deleteFrame,deleteFrame2,deleteFrame3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mContext = getApplicationContext();
        deleteFrame = findViewById(R.id.delete_frame);
        deleteFrame2=findViewById(R.id.delete_frame2);
        deleteFrame3=findViewById(R.id.delete_frame3);
        read_flag = (ImageView) findViewById(R.id.read_flag);
        read_flag.setOnClickListener(this);
        phoneEt = (EditText) findViewById(R.id.phone_number);
        codeEt = (EditText) findViewById(R.id.code_number);
        passwordEt = (EditText) findViewById(R.id.password_number);
        sureBu = (Button) findViewById(R.id.sure);
        look_frame = (FrameLayout) findViewById(R.id.look_frame);
        look_password = (ImageView) findViewById(R.id.look_password);
        getcodeTv = (TextView) findViewById(R.id.get_code);
        sureBu.setOnClickListener(this);
        look_frame.setOnClickListener(this);
        getcodeTv.setOnClickListener(this);
        readLl = findViewById(R.id.read_ll);
//        readLl.setOnClickListener(this);

        findViewById(R.id.register_pro).setOnClickListener(this);
        findViewById(R.id.get_read).setOnClickListener(this);
        baseback.setVisibility(View.VISIBLE);
        initData();
        initView();
    }


    private void initData() {
        basetitle.setText("用户注册");
        deleteFrame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phoneEt.setText("");
            }
        });

        deleteFrame2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                codeEt.setText("");
            }
        });

        deleteFrame3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                passwordEt.setText("");
            }
        });

        phoneEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals("")) {
                    deleteFrame.setVisibility(View.INVISIBLE);
                } else {
                    deleteFrame.setVisibility(View.VISIBLE);
                }
            }
        });

        codeEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals("")) {
                    deleteFrame2.setVisibility(View.GONE);
                } else {
                    deleteFrame2.setVisibility(View.VISIBLE);
                }
            }
        });

        passwordEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals("")) {
                    deleteFrame3.setVisibility(View.GONE);
                } else {
                    deleteFrame3.setVisibility(View.VISIBLE);
                }
            }
        });
    }


    private void initView() {
    /*	Selflistener selflistener = new Selflistener();
        getcodeTv.setOnClickListener(selflistener);
		sureBu.setOnClickListener(selflistener);*/
    }

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            int i = msg.arg1;
            if (i >= 1) {
                getcodeTv.setClickable(false);
                getcodeTv.setText(i + "秒后重新发送");
            } else {
                i = 0;
                getcodeTv.setClickable(true);
                getcodeTv.setText(R.string.getcode_regist);
            }
        }

        ;
    };
    boolean passwordflag = false;
    String password = "";
    boolean readFlag = true;//是否阅读确认相关协议的标志

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
/*            case R.id.read_ll:
            case R.id.read_flag:
            case R.id.get_read:
                if (readFlag == false) {
                    readFlag = true;
                    read_flag.setImageResource(R.mipmap.register_read);
                } else {
                    readFlag = false;
                    read_flag.setImageResource(R.mipmap.register_unread);
                }
                break;*/
            case R.id.register_pro:
                help();
                break;
            case R.id.baseback:
                // 返回上一页
                finish();
                break;
            case R.id.look_frame:
                if (!passwordflag) {
                    look_password.setImageDrawable(getResources().getDrawable(R.mipmap.login_03_));
                    passwordEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    look_password.setImageDrawable(getResources().getDrawable(R.mipmap.login_03));
                    passwordEt.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                passwordflag = !passwordflag;
                passwordEt.postInvalidate();
                CharSequence text = passwordEt.getText();
                if (text instanceof Spannable) {
                    Spannable spanText = (Spannable) text;
                    Selection.setSelection(spanText, text.length());
                }
                break;
            case R.id.get_code:
                // 获取验证码
                if (InputControl.isPhoneNumber(phoneEt) && !isRequestCode) {
                    //isAccount();
                    getcodeTv.setText(R.string.getcode_registing);
                    isRequestCode = true;
                    getCodePost();
                } else {
                    getcodeTv.setClickable(true);
                    ToastUtils.TextToast(getApplicationContext(), "请输入合法的手机号码");
                }

                break;
            case R.id.sure:
                if (InputControl.isEmpty(phoneEt)) {
                    T.toast("请输入手机号");
                    return;
                } else {
                    if (!InputControl.isPhoneNumber(phoneEt)) {
                        T.toast("手机号有误，请改正");
                        return;
                    }
                }
                if (InputControl.isEmpty(codeEt) || codeEt.getText().toString().length() != 4) {
                    T.toast("请输入4位验证码");
                    return;
                }
                if (InputControl.isEmpty(passwordEt) || passwordEt.getText().toString().length() < 6) {
                    T.toast("请输入长度至少为6位的密码");
                    return;
                }
                if (readFlag == true) {} else {
                    ToastUtils.TextToast(this, "请确认相关协议");
                    return;
                }
                register();
                break;
            default:
                break;
        }
    }


    private void help() {

        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra(Constant.KEY_WEB_URL, Constant.URL_HELP_SUPPLIER_AGREEMENT);
        intent.putExtra(Constant.KEY_WEB_TITLE, "e批生鲜用户服务协议");
        startActivity(intent);

    }

    /**
     * 获取验证码按钮倒计时控制
     */
    private void getCodeControl() {
        new Thread() {
            int i = 60;

            public void run() {
                try {
                    while (i > 0) {
                        if (isDestory) {
                            return;
                        }
                        Thread.sleep(999);
                        i--;
                        Message message = new Message();
                        message.arg1 = i;
                        handler.sendMessage(message);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

            ;
        }.start();
    }

    OnRequestListener<StatusEntity> onRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {


        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                Intent main = new Intent(getApplicationContext(), LoginActivity.class);
                main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// 清空已存在的所有Activity
                startActivity(main);
                finish();
                T.toast(BaseApplication.getDoc().getRegSuccess());
                return;
            }

        }
    };

    /**
     * 注册
     */
    private void register() {

        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
        data.setCmd(AppSupplyRouterConstant.CMD_REGISTER);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, String> map = new HashMap<>();
        map.put("phone", phoneEt.getText().toString());
        map.put("password", passwordEt.getText().toString());
        map.put("verification", codeEt.getText().toString());
        data.setParameters(map);
        request(data, "register", onRequestListener);
    }

    OnRequestListener<StatusEntity> onRequestCodeListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            isRequestCode = false;

            getcodeTv.setClickable(true);
            getcodeTv.setText(R.string.getcode_regist);
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            //token超时
            hideProgressDialog();
            isRequestCode = false;
            getcodeTv.setClickable(true);
            getcodeTv.setText(R.string.getcode_regist);
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
            hideProgressDialog();
            isRequestCode = false;
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                getcodeTv.setClickable(false);
                getCodeControl();
            } else {
                getcodeTv.setText(R.string.getcode_regist);
            }

            return;
        }
    };

    /**
     * 注册
     */
    private void getCodePost() {

        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
        data.setCmd(AppSupplyRouterConstant.CMD_GETCODE);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, String> map = new HashMap<>();
        map.put("phone", phoneEt.getText().toString());
        map.put("type", "1");
        data.setParameters(map);
        request(data, "getVerification", onRequestCodeListener);
    }

    @Override
    protected void onDestroy() {
        isDestory = true;
        RequestManager.getInstance().cancel("register");
        onRequestListener = null;
        RequestManager.getInstance().cancel("getVerification");
        onRequestCodeListener = null;
        super.onDestroy();
    }
}